<template>
	<view class="router-view bcl-active" style="padding: 30rpx 80rpx;">
		<!-- LOGO -->
		<!-- <view class="logo mt-30">
      <image class="block" src="/static/images/logo.png" mode="widthFix" />
    </view> -->

		<!-- 表单 -->
		<view class="form mt-40 mb-20">
			<!-- 登录 -->
			<view class="form-login" v-if="type == 1">
				<view class="uni-input uni-input-user">
					<input type="text" placeholder="用户名/邮箱地址/手机号码" v-model="username" />
				</view>
				<view class="uni-input uni-input-password">
					<input type="text" :password="true" placeholder="请输入密码" v-model="password" />
				</view>
			</view>

			<!-- 手机登录/忘记密码/注册 -->
			<view class="form-phone-login" v-else-if="type != 1 && type != 5">
				<view class="uni-input uni-input-tel">
					<input type="tel" placeholder="请输入手机号码" v-model="tel" />
				</view>
				<view class="uni-input uni-input-code" v-if="type != 2">
					<input type="number" placeholder="请输入验证码" v-model="smsCode" />

					<!-- 发送验证码按钮 -->
					<view class="send-btn cl-main pointer" :disabled="counting" @tap="sendSmsCode">{{ countText }}</view>
				</view>
				<view class="uni-input uni-input-password" v-if="type != 2">
					<input type="text" :password="true" :placeholder="type == 4 ? '请输入新的密码' : '请输入密码'" v-model="password" />
				</view>
				<view class="uni-input uni-input-password" v-if="type != 2">
					<input type="text" :password="true" placeholder="再次确认密码" v-model="rePassword" />
				</view>
			</view>

			<!-- 发送验证码 -->
			<view class="form-code text-center" v-else>
				<div class="fz-20 bold">输入验证码</div>
				<div class="mt-10 mb-10">短信已发送至{{ tel }}</div>
				<div class="mb-20">
					<password-input :length="4" @complete="phoneLogin" v-model="smsCode"></password-input>
				</div>
				<div @click="sendSmsCode">{{ countText }}</div>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn" v-if="type != 5">
			<button class="uni-button uni-button-full uni-button-lg" @tap="submit">
				{{
          type == 3
            ? "立即注册"
            : type == 4
            ? "找回密码"
            : type == 2
            ? "获取验证码"
            : "立即登录"
        }}
			</button>
		</view>

		<!-- 切换按钮 -->
		<view class="toggle-btn box box-between mt-20" v-if="type != 5">
			<view class="pointer pointer-filter" @tap="type = 2" v-if="type == 1">手机登录</view>
			<view class="pointer pointer-filter" @tap="type = 1" v-if="type == 2">账号密码登录</view>
			<view class="cl-second fz-12" v-if="type == 2">未注册手机验证后自动注册</view>
			<view v-if="type == 3 || type == 4">
				<text>{{ type == 3 ? "已有账号？" : "已记起密码？" }}</text>
				<text class="pointer pointer-filter cl-main" @tap="type = 1">前往登录</text>
			</view>
			<view class="pointer pointer-filter cl-main" @tap="type = 4" v-if="type == 1">忘记密码?</view>
		</view>

		<!-- 注册协议 -->
		<view class="box box-column-center fz-12 mt-10 mb-20" v-if="type != 5">
			<checkbox-group @change="onProtocolChange">
				<label>
					<checkbox value="同意" :checked="protocol" />
					<text class="cl-second middle">我已阅读并同意</text>
				</label>
			</checkbox-group>
			<navigator url="/user/plan?type=6" v-if="type == 3">《用户注册协议》</navigator>
			<navigator url="/user/plan?type=5" v-else>《志华网服务条款》</navigator>
		</view>

		<!-- 底部按钮 -->
		<view class="footer-btn mt-50 text-center" v-if="type == 1 || type == 2">
			<!-- <button
        class="uni-button uni-button-full uni-button-lg uni-button-unfill"
        @tap="type = 3"
      >
        新用户注册
      </button> -->

			<!-- #ifdef MP-WEIXIN -->
			<button class="wechat-btn mt-10" open-type="getUserInfo" @getuserinfo="toWxLogin">
				<image src="/static/share/icon_weixin.png" style="width: 80rpx; height: 80rpx;"></image>
			</button>
			<!-- #endif -->

			<!-- #ifdef APP-PLUS -->
			<button class="wechat-btn mt-10" open-type="getUserInfo" @click="toWxLogin">
				<image src="/static/share/icon_weixin.png" style="width: 80rpx; height: 80rpx;"></image>
			</button>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from "vuex";
	import regexp from "@/utils/regexp";

	import {
		login,
		register,
		reset,
		sendSmsCode,
		checkRegisterSmsCode,
		checkResetSmsCode,
		wxLogin,
		telLoginSendCode,
		telLogin,
	} from "@/apis/user";

	import passwordInput from "@/components/passwordInput";

	export default {
		data() {
			return {
				username: "",
				tel: "",
				smsCode: "",
				password: "",
				rePassword: "",

				navigationBarTitles: {
					1: "账号密码登录",
					2: "手机号码登录",
					3: "新用户注册",
					4: "忘记密码",
				},

				protocol: true, // 是否同意协议
				type: 2, // 页面类型

				count: 60, // 验证码总倒计时数
				counting: false, // 正在倒计时
			};
		},

		async onLoad() {
			this.gotoTest()
			// 修改页面标题
			uni.setNavigationBarTitle({
				title: this.navigationBarTitles[this.type],
			});
		},

		methods: {
			gotoTest() {
				uni.$emit('emit')

			},
			callback(e) {
				console.log("eee", e)
			},
			/*
			 * 提交分发
			 */
			submit() {
				if (!this.protocol) return this.$toast("请先同意协议");
				if (this.type == 1) return this.login();
				// 发送验证码
				else if (this.type == 2) return this.sendSmsCode(true);
				else if (this.type == 3 || this.type == 4) return this.checkSmsCode();
			},

			/*
			 * 登录
			 */
			async login() {
				if (!this.username) return this.$toast("请输入用户名");
				if (!this.password) return this.$toast("请输入密码");

				let params = {
					username: this.username,
					password: this.password,
				};

				let {
					code,
					data
				} = await login(params);

				if (code == 200) {
					this.$toast("登录成功");
					this.resetForm();
					data && this.SET_USER_INFO(data);
					this.logoutTIM();
					this.loginSucessCallback();
				}
			},

			/*
			 * 手机号登录
			 */
			async phoneLogin() {
				if (!regexp.tel.test(this.tel)) return this.$toast("请输入正确的手机号");
				if (!this.smsCode) return this.$toast("请输入手机验证码");

				let params = {
					mobile: this.tel,
					code: this.smsCode,
				};

				let {
					code,
					data
				} = await telLogin(params);

				if (code === 200) {
					this.$toast("登录成功");
					this.resetForm();
					data && this.SET_USER_INFO(data);
					this.logoutTIM();
					this.loginSucessCallback();
				}
			},

			/*
			 * 注册/找回密码
			 */
			async registerOrReset() {
				if (!regexp.tel.test(this.tel)) return this.$toast("请输入正确的手机号");
				if (!this.smsCode) return this.$toast("请输入手机验证码");
				if (!this.password)
					return this.$toast(this.type == 4 ? "请输入新的密码" : "请输入密码");
				if (!this.rePassword) return this.$toast("请输入确认密码");
				if (this.password != this.rePassword)
					return this.$toast("两次输入的密码不一致");

				let params = {
					username: this.tel,
					password: this.password,
					source: 2,
				};

				// 忘记密码的参数处理
				if (this.type == 4) {
					params.repassword = this.rePassword;
					delete params.username;
					delete params.source;
				}

				let {
					code,
					data
				} =
				this.type == 3 ? await register(params) : await reset(params);

				if (code == 200) {
					this.$toast(this.type == 3 ? "注册成功" : "请重新登录");
					this.resetForm();
					if (this.type == 3) {
						data && this.SET_USER_INFO(data);
						this.logoutTIM();
						this.loginSucessCallback();
					} else {
						this.type = 1;
					}
				}
			},

			/*
			 * 发送手机验证码
			 */
			async sendSmsCode() {
				if (this.counting) return false;
				if (!regexp.tel.test(this.tel)) return this.$toast("请输入正确的手机号");

				this.sending = true;

				// 手机号登录发送验证码用 telLoginSendCode 接口
				if (this.type == 2) {
					let params = {
						mobile: this.tel,
					};
					let {
						code,
						data
					} = await telLoginSendCode(params);

					if (code == 200) {
						this.$toast("发送成功");
						this.countDown();
						this.type = 5;
					}
				} else {
					let params = {
						phone: this.tel,
						type: this.type == 3 ? 1 : 2,
					};
					let {
						code,
						data
					} = await sendSmsCode(params);

					if (code == 200) {
						this.$toast("发送成功");
						this.countDown();
					}
				}
			},

			/*
			 * 验证注册/找回密码手机验证码
			 */
			async checkSmsCode() {
				if (!regexp.tel.test(this.tel)) return this.$toast("请输入正确的手机号");
				if (!this.smsCode) return this.$toast("请输入手机验证码");

				let params = {
					phone: this.tel,
					code: this.smsCode,
				};

				let {
					code,
					data
				} =
				this.type == 3 ?
					await checkRegisterSmsCode(params) :
					await checkResetSmsCode(params);

				if (this.type == 4) {
					let userInfo = {
						...this.userInfo,
					};
					userInfo.token = data.token;
					userInfo && this.SET_USER_INFO(userInfo);
					this.logoutTIM();
				}

				if (code == 200) this.registerOrReset();
				else this.smsCode = "";
			},

			/*
			 * 验证码倒计时
			 */
			countDown() {
				let count = this.count;
				this.counting = true;

				let interval = setInterval(() => {
					this.count -= 1;

					// 倒计时结束
					if (this.count == 0) {
						this.counting = false;
						this.count = count;
						clearInterval(interval);
					}
				}, 1000);
			},

			onProtocolChange(event) {
				let value = event.detail.value[0];
				this.protocol = !!value;
			},

			/**
			 * 微信授权登录
			 */
			async toWxLogin(e) {
				let params = {
					code: "",
					data: {},
					type: "",
				};

				// app 端微信登录
				// #ifdef APP-PLUS
				let [errCode, resCode] = await uni.login({
					provider: "weixin"
				});
				// params.code = resCode.code;

				let [errUserInfo, resUserInfo] = await uni.getUserInfo({
					provider: "weixin",
				});
				params.data = resUserInfo.userInfo;

				params.type = "app";
				// #endif

				// 小程序端微信登录
				// #ifdef MP-WEIXIN
				let [err, res] = await uni.login();
				console.log("----->小程序微信登录，返回数据：",res,e);
				params = {
					data: e.detail,
					code: res.code,
					type: "xcx",
				};
				// #endif

				console.log("params", params);
				try {
					let reps = await wxLogin(params);
					let {
						code,
						data,
						message
					} = reps;
					console.log(reps);
					if (code === 200) {
						this.$toast("登录成功");
						data && this.SET_USER_INFO(data);
						this.logoutTIM();
						this.loginSucessCallback();
					}
				} catch (e) {
					console.log("error", e);
				}
			},

			loginSucessCallback() {
				console.log(this.userInfo);
				setTimeout(() => {
					if (this.userInfo.is_mobile === undefined || this.userInfo.is_mobile === null || this.userInfo.is_mobile === 0) {
						// 没有绑定手机
						uni.redirectTo({
							url: "/user/setting/binding/tel",
						});
					} else if (this.userInfo.is_realname === undefined || this.userInfo.is_realname === null || this.userInfo.is_realname ===
						0) {
						// 没有实名认证
						// uni.redirectTo({
						// 	url: "/user/setting/binding/name",
						// });
						// 返回上一页
						uni.navigateBack({
							delta: 1
						});
					} else {
						// 返回上一页
						uni.navigateBack();
					}


				}, 1000);
			},

			logoutTIM() {
				if (this.tim) {
					this.tim.logout().then((aaa) => {
						this.SET_TIM("");
						uni.setStorageSync("timUserSign", "");
					});
				} else {
					this.SET_TIM("");
					uni.setStorageSync("timUserSign", "");
				}
			},

			resetForm() {
				this.username = "";
				this.tel = "";
				this.smsCode = "";
				this.password = "";
				this.rePassword = "";
			},

			...mapActions(["SET_USER_INFO", "SET_TIM"]),
		},

		watch: {
			type: function() {
				if (this.type != 5) {
					this.resetForm();

					// 修改页面标题
					uni.setNavigationBarTitle({
						title: this.navigationBarTitles[this.type],
					});
				}
			},
		},

		components: {
			passwordInput,
		},

		computed: {
			countText() {
				if (!this.counting) {
					return "获取验证码";
				} else {
					return `${this.count}s后重新获取`;
				}
			},
			...mapState(["userInfo", "tim"]),
		},
	};
</script>

<style lang="scss" scoped>
	.router-view {
		.logo {
			image {
				width: 350upx;
				margin: 0 auto;
			}
		}

		.wechat-btn {
			display: inline-block;

			&::after {
				border: none;
			}
		}
	}
</style>
